package com.niiwoo.civet.trade.service.local.project;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.niiwoo.activity.event.enums.FlowProjectTypeEventEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectFlowed;
import com.niiwoo.civet.trade.dao.mapper.ProjectFlowedMapper;
import com.niiwoo.civet.trade.dao.mapper.ProjectFlowedMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dto.request.ProjectFlowRequestDTO;
import com.niiwoo.civet.trade.enums.ProjectSubStatusEnum;
import com.niiwoo.civet.trade.service.local.activity.ActivityEventService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.tripod.lanmao.component.LanMaoDirectService;
import com.niiwoo.tripod.lanmao.component.LanMaoSequence;
import com.niiwoo.tripod.lanmao.enums.ProjectStatusEnum;
import com.niiwoo.tripod.lanmao.request.ModifyProjectRequest;
import com.niiwoo.tripod.lanmao.request.QueryProjectInformationRequest;
import com.niiwoo.tripod.lanmao.response.ModifyProjectResponse;
import com.niiwoo.tripod.lanmao.response.QueryProjectInformationResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by dell on 2018/1/12.
 */
@Service
@Slf4j
public class ProjectFlowService {

    @Autowired
    private ProjectMapperExt projectMapperExt;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;

    @Autowired
    ProjectFlowedMapperExt projectFlowedMapperExt;
    @Autowired
    LanMaoSequence lanMaoSequence;
    @Autowired
    LanMaoDirectService lanMaoDirectService;
    @Autowired
    ActivityEventService activityEventService;

    public void overInvestEndTimeFlow() {
        List<Project> projects = projectMapperExt.selectListOverInvestEndTime();
        for (Project project : projects) {
            try {
                ProjectFlowRequestDTO requestDTO = new ProjectFlowRequestDTO();
                requestDTO.setProjectId(project.getProjectId());
                requestDTO.setSubStatus(ProjectSubStatusEnum.MISCARRY_INVEST_OVERTIME);
                requestDTO.setRemark(ProjectSubStatusEnum.MISCARRY_INVEST_OVERTIME.getDesc());
                projectDubboService.flow(requestDTO);

                activityEventService.sendMsgForFlowProject(project.getProjectId(), FlowProjectTypeEventEnum.INVEST_UNDER_FLOW);
            } catch (Exception e) {
                log.error("借款用户标的筹款超时流标失败，projectId=" + project.getProjectId(), e);
            }
        }
    }

    public List<ProjectFlowed> getUnsyncFlowList() {
        return projectFlowedMapperExt.selectUnSyncFLow();
    }

    public void syncSingleFlowStatus(ProjectFlowed pf) {
        // 同步标的状态到存管
        ModifyProjectRequest modifyProjectRequest = new ModifyProjectRequest();
        modifyProjectRequest.setProjectNo(String.valueOf(pf.getProjectId()));
        modifyProjectRequest.setStatus(ProjectStatusEnum.MISCARRY);
        modifyProjectRequest.setRequestNo(lanMaoSequence.getRequestNo());
        ModifyProjectResponse response;
        try {
            log.info("同步流标状态到存管计划任务###变更标的状态###请求={}", JSON.toJSONString(modifyProjectRequest));
            response = lanMaoDirectService.modifyProject(modifyProjectRequest).get();
            log.info("同步流标状态到存管计划任务###变更标的状态###响应={}", JSON.toJSONString(response));
        } catch (Exception e) {
            log.error(String.format("同步流标状态到存管计划任务###变更标的状态###异常=%s", e.getMessage()), e);
            return;
        }
        // 同步成功， 修改记录状态
        if (response.isSuccess()) {
            ((ProjectFlowService) AopContext.currentProxy()).markHasSynced(pf);
            return;
        }
        // 失败则查询标的状态, 如果存管标的状态是流标， 将修改状态记录
        QueryProjectInformationRequest queryProjectInformationRequest = new QueryProjectInformationRequest();
        queryProjectInformationRequest.setProjectNo(String.valueOf(pf.getProjectId()));
        queryProjectInformationRequest.setRequestNo(lanMaoSequence.getRequestNo());
        try {
            log.info("同步流标状态到存管计划任务###查询标的信息###请求={}", JSON.toJSONString(modifyProjectRequest));
            QueryProjectInformationResponse queryProjectInformationResponse = lanMaoDirectService.queryProjectInformation(queryProjectInformationRequest).get();
            log.info("同步流标状态到存管计划任务###查询标的信息###响应={}", JSON.toJSONString(queryProjectInformationResponse));
            if (queryProjectInformationResponse.isSuccess() && queryProjectInformationResponse.getProjectStatus() == ProjectStatusEnum.MISCARRY) {
                ((ProjectFlowService) AopContext.currentProxy()).markHasSynced(pf);
            } else {
                log.error("同步流标状态到存管计划任务###查询标的信息###标的状态异常, projectId={}", pf.getProjectId());
            }
        } catch (Exception e) {
            log.error(String.format("同步流标状态到存管计划任务###查询标的信息###异常=%s", e.getMessage()), e);
        }
    }

    @Transactional
    public boolean markHasSynced(ProjectFlowed pf) {
        ProjectFlowed projectFlowed = new ProjectFlowed();
        projectFlowed.setProjectId(pf.getProjectId());
        projectFlowed.setSyncStatus((byte) 1);
        projectFlowed.setSyncSuccessTime(new Date());
        return projectFlowedMapperExt.updateSyncStatus(projectFlowed) > 0;
    }

    @Transactional
    public boolean add(ProjectFlowed pf) {
        return projectFlowedMapperExt.insertSelective(pf) > 0;
    }

}
